package com.mengsenlin.service;

import com.mengsenlin.entity.Result;
import com.mengsenlin.entity.ShoppingCart;
import com.mengsenlin.entity.User;
import com.mengsenlin.mapper.CartMapper;
import com.mengsenlin.mapper.UserMapper;
import com.mengsenlin.tool.GsonUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.net.URLDecoder;
import java.util.List;

/**
 * Created by Administrator on 2017/7/15.
 */
@Service
public class UserService {
    @Autowired
    UserMapper userMapper;
    @Autowired
    CartMapper cartMapper;

    public Result<User> signIn(String userName, String password, HttpSession session, HttpServletRequest request){
        User user = userMapper.selectUserByuserNameAndPassword(userName, password);
        Result<User> result;
        if(null == user || user.getDelFlag() == 1){
            result = new Result<User>(false, "The account or password error");
        }else{
            result = new Result<User>(true, user);
            session.setAttribute("user", user);
            Cookie[] cookies = request.getCookies();
            cookieToCart(cookies, user.getId());
        }
        return result;
    }

    public void cookieToCart(Cookie[] cks, long userId) {
        try{
            if(cks != null) {   //如果请求中存在Cookie
                for(Cookie c : cks) {//遍历所有Cookie
                    if(c.getName().equals("cart")) {//获取Cookie名字
                        String cartStr = c.getValue();
                        String cartStrDecode = URLDecoder.decode(cartStr, "utf-8");
                        List<ShoppingCart> shoppingCarts = GsonUtil.parseJsonArrayWithGson(cartStrDecode, ShoppingCart.class);
                        System.out.println(shoppingCarts);
                        cartMapper.insertCartFromCookie(userId, shoppingCarts);
                    }
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    public Result<User> signUp(String userName, String password, String phoneNum){
        User user = userMapper.selectUserByuserName(userName);
        Result<User> result;
        if(null != user){
            result = new Result<User>(false, "The account has existed");
            return result;
        }else{
            int i = userMapper.insertUser(userName, password, phoneNum);
            if(i < 1){              //插入失败
                result = new Result<User>(false, "注册失败，请稍后重试或者联系系统管理员");
                return result;
            }
        }
        result = new Result<User>(true);
        return result;
    }

    public Result<User> modify(String userName, String password, String phoneNum,
                               HttpSession session){
        User user=(User)session.getAttribute("user");
        long userId = user.getId();
        String olduserName = user.getUserName();
        Result<User> result;
        if(olduserName.equals(userName)){
            result = new Result<User>(false, "修改失败，该用户名已存在！");
            return result;
        }
        int i = userMapper.updateUserById(userName,password,phoneNum,userId);
            if(i < 1){
                result = new Result<User>(false, "修改失败，请稍后重试!");
                return result;
            }

        result = new Result<User>(true);
        user = userMapper.selectUserByuserName(userName);
        session.setAttribute("user",user);
        return result;
    }

    public Result<User> cutOut(String userName){
        int  i = userMapper.deleteUser(userName);
        Result<User> result;
        if(i < 1){
            result = new Result<User>(false, "操作失败，请稍后重试!");
        }else{
            result = new Result<User>(true);
        }
        return result;
    }

    public Result<User> logOut(HttpSession session){
        Result<User> result;
        if(session != null && session.getAttribute("user") != null){
            session.setAttribute("user",null);
            result = new Result<User>(true);
            return result;
        }
        result = new Result<User>(false, "操作失败，请稍后重试！");
        return result;
    }
}
